// pages/mine/joinMerchant/merchantTwo/merchantTwo.js
import Toast from '../../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast';
import Dialog from '../../../../miniprogram/miniprogram_npm/vant-weapp/dialog/dialog';
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    isPartner1: false,
    timeList: ['01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00'
      , '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '24:00'],
    merchantInfo: {},
    legalName: '',
    legalNo: '',
    startTime: '请选择上班时间',
    endTime: '请选择下班时间',
    busiLicenseImg: '',
    handIdPhoto: '',
    logo: '',
    signageImg: '',
    otherLicenseImg: '',
    latitude:'',
    longitude:'',
    status:'',

    edition: '',//版本信息
    editionIndex: '',
    isShowEdition: false,
    editionColumns: [],
    submitDis: false,
    upid: '',//推荐人id
    upname: '',//推荐人name
    centreId: '',//上个页面传参，重新提交接口使用
    dataOrderId: '',
    payStatus: '',
    selectXieyi:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    let selectXieyi = wx.getStorageSync('selectXieyi');
    this.setData({
      user: app.getUser(),
      merchantInfo: JSON.parse(wx.getStorageSync('merchantInfo')),
      upid: event.upid || '',
      upname: event.upname || '',
      centreId: app.globalData.loginCentreId,
      selectXieyi:selectXieyi,
    });
    this.inspect();
    this.columnsEditionData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  //合伙人状态校验
  inspect(){
    let _this = this;
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/centre/getInfo',
      data: {
        mid: _this.data.user.id
      }
    }).then(res =>{
      let dd = res.data.data;
      if(dd == '') return;
      _this.setData({
        legalName: dd.legalName,
        legalNo: dd.legalNo,
        startTime: dd.workStart,
        endTime: dd.workEnd,
        busiLicenseImg: dd.busiLicenseImg,
        handIdPhoto: dd.handIdPhoto,
        logo: dd.logo,
        signageImg: dd.signageImg,
        otherLicenseImg: dd.otherLicenseImg,
        status: dd.status,
        payStatus: dd.payStatus,
        'edition.name': dd.projectexpName,
        'edition.id': dd.projectexpId,
        'edition.price': dd.projectexpPrice,
      })
      //已购买版本
      if (dd.payStatus == 2 && dd.status == 1) {
//        Dialog.alert({
//          title: '提示',
//          message: '你已购买版本',
//        }).then(() => {
//          _this.setData({submitDis: true})
//        })
// else if(dd.payStatus == 0){
//   Dialog.alert({
//     title: '提示',
//     message: '你已下单请去支付',
//   }).then(() => {
//     _this.setData({submitDis: true})
//   })
// } 
        _this.setData({submitDis: true})
      } else if (dd.payStatus != 2 && dd.status == 2) {//请去支付
        Dialog.alert({
          title: '提示',
          message: '你已下单请去支付',
        }).then(() => {
          _this.setData({submitDis: true})
        })
      }else if (dd.payStatus == 2 && dd.status == 2) {//审核中
        Dialog.alert({
          title: '提示',
          message: '正在审核中',
        }).then(() => {
          _this.setData({submitDis: true})
        })
      } else if (dd.status == 3) {//已拒绝
        Dialog.alert({
          title: '提示',
          message: '审核被拒绝，可重新提交',
        }).then(() => {
        })
      }
    })
  },

  //版本数据源
  columnsEditionData() {
    let _this = this;
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/getProjectExp',
      data: {
        offset: 0,
        limit: 0,
      },
    }).then(res =>{
      _this.setData({
        editionColumns: res.data.data.rows
      })
    })
  },
  editionMonitor(){
    let _this = this;
    if(_this.data.status == 3) return;//已拒绝，无法更换版本
    _this.setData({
      isShowEdition: !_this.data.isShowEdition
    })
  },
  editionConfirm(event){
    this.setData({
      edition: event.detail.value
    })
    this.editionMonitor();
  },

  partnerConfirm1(event) {
    let _this = this;
    let index = event.detail.index;
    _this.setData({
      startTime: event.detail.value,
    })
    _this.isPartnerMonitor1();
  },
  isPartnerMonitor1() {
    let _this = this;
    _this.setData({
      isPartner1: !_this.data.isPartner1
    })
  },
  partnerConfirm2(event) {
    let _this = this;
    let index = event.detail.index;
    _this.setData({
      endTime: event.detail.value,
    })
    _this.isPartnerMonitor2();
  },
  isPartnerMonitor2() {
    let _this = this;
    _this.setData({
      isPartner2: !_this.data.isPartner2
    })
  },
  onChangeLegalName: function (event) {
    this.setData({
      legalName: event.detail
    })
  },
  onChangeLegalNo: function (event) {
    this.setData({
      legalNo: event.detail
    })
  },
  // 上传
  upload: function (event) {
    var _this = this;
    wx.chooseImage({
      count: 1, //最多可以选择的图片总数  
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有  
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有  
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        var tempFilePaths = res.tempFilePaths;
        //启动上传等待中...  
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 500
        });
        wx.uploadFile({
          url: app.globalData.deployUrl + '/platform/config/upload',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: { user: 'test' },
          success: function (res) {
            console.log(event.currentTarget.dataset.status);
            let data = JSON.parse(res.data);
            if (event.currentTarget.dataset.status == "busiLicenseImg") {
              _this.setData({
                'busiLicenseImg': data.key,
              })
            } else if (event.currentTarget.dataset.status == "handIdPhoto") {
              _this.setData({
                'handIdPhoto': data.key,
              })
            } else if (event.currentTarget.dataset.status == "logo") {
              _this.setData({
                'logo': data.key,
              })
            } else if (event.currentTarget.dataset.status == "signageImg") {
              _this.setData({
                'signageImg': data.key,
              })
            } else if (event.currentTarget.dataset.status == "otherLicenseImg") {
              _this.setData({
                'otherLicenseImg': data.key,
              })
            }

          },
          fail: function (res) {
            wx.hideToast();
            wx.showToast({
              title: '上传图片失败',
              icon: 'none'
            });
          }
        });
      }
    });
  },
  // 提交
  getApply: function (event) {
    let that = this;
    let data = that.data;
    let merchantInfo = data.merchantInfo;
    if (!data.legalName) {
      Toast('请填写姓名'); return;
    } else if (!data.legalNo) {
      Toast('请填写身份证号'); return;
    } else if (data.startTime == '请选择上班时间') {
      Toast('请选择上班时间'); return;
    } else if (data.endTime == '请选择下班时间') {
      Toast('请选择下班时间'); return;
    } else if (data.edition == '') {
      Toast('请选择版本'); return;
    } else if (!data.busiLicenseImg) {
      Toast('请上传营业执照'); return;
    } else if (!data.handIdPhoto) {
      Toast('请上传身份证照片'); return;
    } else if (!data.logo) {
      Toast('请上传店铺Logo'); return;
    } else if (!data.signageImg) {
      Toast('请上传店招图'); return;
    } else if(!data.selectXieyi) {
      Toast('请阅读并接受用户协议'); return;
    }

    if( event.currentTarget.dataset.type == 'again'){
      that.againSubmit();
      return;
    }

    that.prepare();
  },

  //重新提交
  againSubmit(){
    let _this = this;
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/centre/applyCentre/update',
      data: {
        centreId: app.globalData.loginCentreId,//关键参数
        status: 2,//关键参数
        name: _this.data.legalName,
        accountMobile: _this.data.merchantInfo.accountMobile,
        paymentdays: 1,
        projectexpId: _this.data.edition.id,//版本id
        projectexpName: _this.data.edition.name,//版本名字
        projectexpPrice: _this.data.edition.price,//版本价格
        type: 0,
        referrals: _this.data.upid,//推荐人id

        province: _this.data.merchantInfo.province,
        city: _this.data.merchantInfo.city,
        area: _this.data.merchantInfo.area,
        address: _this.data.merchantInfo.address,
        pcate: _this.data.merchantInfo.selectFirstId,
        ccate: _this.data.merchantInfo.selectSecondId,
        legalName: _this.data.legalName,
        legalNo: _this.data.legalNo,
        startTime: _this.data.startTime,
        endTime: _this.data.endTime,
        busiLicenseImg: _this.data.busiLicenseImg,
        handIdPhoto: _this.data.handIdPhoto,
        logo: _this.data.logo,
        signageImg: _this.data.signageImg,
        otherLicenseImg: _this.data.otherLicenseImg,
        lat: _this.data.merchantInfo.latitude,
        lon: _this.data.merchantInfo.longitude,
      },
      header: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': wx.getStorageSync('authToken') || 'empty-token'
      },
    }).then(res =>{
      Dialog.alert({
        title: '提示',
        message: '重新提交成功，请等待审核'
      }).then(res =>{
        wx.switchTab({
          url: '/pages/user/user',
        })
      })
    })
  },

  //预提交接口
  prepare() {
    let _this = this;
    _this.setData({submitDis: true})
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/order/precreate',
      data: {
        memberId: _this.data.user.id,
        isCentreord: 1,
        projectExpId: _this.data.edition.id,
        products: [{
          cartId: 0,
          productId: 0,
          total: 1,
          marketprice: _this.data.edition.price,
        }]
      },
      header: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': wx.getStorageSync('authToken') || 'empty-token'
      },
    }).then(res =>{
      //添加订单
      _this.newCreat();
    })
  },
  //添加订单接口
  newCreat() {
    let _this = this;
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/order/create',
      data: {
        memberId: _this.data.user.id,
        referrals: _this.data.upid,//推荐人id
        products: [{
          id: 0 + ':null',
          productId: 0,
          total: 1,
          mid: _this.data.user.id,
          openid: _this.data.user.openid,
          teamid: _this.data.user.upshopTid,
          centreId: app.globalData.loginCentreId,
        }],
        sname: _this.data.legalName,
        mobile: _this.data.merchantInfo.accountMobile,
        houseNo: "",
        couponId: null,
        Authorization: wx.getStorageSync('authToken'),
        allweight: 0,
        dispatchprice: 0,
        dispatchid: 0,
        isCentreord: 1,//传1为版本订单
        projectExpId: _this.data.edition.id
      },
      header: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': wx.getStorageSync('authToken') || 'empty-token'
      },
    }).then(res =>{
      //获取订单id
      _this.data.dataOrderId = res.data.data;

      //添加合伙人
      _this.saveIdentity();
    })
  },

  //添加合伙人接口
  saveIdentity() {
    let _this = this;
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/centre/save',
      data: {
        mid: _this.data.user.id,
        name: _this.data.legalName,
        accountMobile: _this.data.merchantInfo.accountMobile,
        areas: _this.data.merchantInfo.area,
        paymentdays: 1,
        projectexpId: _this.data.edition.id,//版本id
        projectexpName: _this.data.edition.name,//版本名字
        projectexpPrice: _this.data.edition.price,//版本价格
        type: 0,
        referrals: _this.data.upid,//推荐人id


        province: _this.data.merchantInfo.province,
        city: _this.data.merchantInfo.city,
        area: _this.data.merchantInfo.area,
        address: _this.data.merchantInfo.address,
        pcate: _this.data.merchantInfo.selectFirstId,
        ccate: _this.data.merchantInfo.selectSecondId,
        legalName: _this.data.legalName,
        legalNo: _this.data.legalNo,
        startTime: _this.data.startTime,
        endTime: _this.data.endTime,
        busiLicenseImg: _this.data.busiLicenseImg,
        handIdPhoto: _this.data.handIdPhoto,
        logo: _this.data.logo,
        signageImg: _this.data.signageImg,
        otherLicenseImg: _this.data.otherLicenseImg,
        lat: _this.data.merchantInfo.latitude,
        lon: _this.data.merchantInfo.longitude,
      },
    }).then(res =>{
      if (res.data.code == 1) {//操作失败，每个账号只能申请一次
        return
      }
      _this.orderOrder();
    })
  },
  //准备支付
  orderOrder() {
    let _this = this;
    let shop = app.getShop();
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/order/',
      data: {
        orderId: _this.data.dataOrderId,
        id: '',
        iskuaidi: '',
        shopId: shop ? shop.id : '',
        Authorization: wx.getStorageSync('authToken'),
        number: Math.random()
      }
    }).then(res =>{
      //支付
      _this.paymentMoney();
    })
  },
  //支付
  paymentMoney(){
    let _this = this;
    let user = app.getUser();
    if(!user.appOpenid){//支付授权
      wx.navigateTo({
        url: '/pages/login-pay/login-pay'
      })
    } else {
      app.requestUrl({
        method: 'GET',
        url: '/wxapi/order/apppay',
        data: {
          orderId: _this.data.dataOrderId,
          couponId: '',
          points: '',
        }
      }).then(res =>{
        let party = {};
        let respData = res.data.data.respData;
        if(respData){
          party.addId = respData.payAppId;
          party.nonceStr = respData.paynonceStr;
          party.package = respData.payPackage;
          party.paySign = respData.paySign;
          party.signType = respData.paySignType;
          party.timeStamp = respData.payTimeStamp;
        }
        //兼容微信支付，第三方支付
        let last = respData ? party : res.data.data;
        wx.requestPayment({
          ...last,
          success: function(d) {
            Dialog.alert({
              title: '提示',
              message: '支付成功，请等待审核'
            }).then(res =>{
              wx.switchTab({
                url: '/pages/user/user',
              })
            })
          },
          fail: function(d) {
            Dialog.alert({
              title: '提示',
              message: '支付失败'
            })
          }
        })
      }).finally(res =>{
        console.log(res)
      })
    }
  },
  //选中协议
  selectXieyiFunction:function(){
    let that = this;
    that.setData({
      selectXieyi:!that.data.selectXieyi
    });
    wx.setStorageSync('selectXieyi',that.data.selectXieyi);
    console.log(wx.getStorageSync('selectXieyi'));
  },
  jumpxieyi:function(){
    wx.navigateTo({
      url: 'xieyi/xieyi',
    })
  },
})